package com.tianpengtech.front.mobile.passport;

import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.fairauth.FairAuth;
import com.tianpengtech.common.model.fairext.FairExt;
import com.tianpengtech.common.model.fairphoto.FairPhoto;
import com.tianpengtech.common.model.fairwithdraw.FairWithdraw;
import com.tianpengtech.common.model.moneylog.MoneyLog;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.common.util.QiNiuUtil;
import com.tianpengtech.front.mobile.common.util.R;
import com.tianpengtech.front.mobile.common.util.U;
import com.tianpengtech.front.mobile.common.util.UserUtil;
import com.tianpengtech.front.mobile.task.TaskCalculateService;
import com.tianpengtech.front.web.common.controller.BaseController;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by ggd on 2017/7/25 0025.
 */
public class MobilePassportController extends BaseController{

    private static MobilePassportService ps = MobilePassportService.me;

    
    public void updateNickName(){
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	String nickName = getPara(Fair.NICK_NAME);
    	R r = ps.updateNickName(user.getLong(User.ID), nickName);
    	renderJson(r);
    }
    
    
    public void updateDescript(){
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	String descript = getPara(Fair.DESCRIPT);
    	R r = ps.updateDescript(user.getLong(User.ID), descript);
    	renderJson(r);
    }
    
    
    public void updateBgPhoto(){
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	String bgPhoto = getPara(Fair.BG_PHOTO);
    	long photo_id = getParaToLong("photo_id");
    	R r = ps.updateBgPhoto(user.getLong(User.ID), bgPhoto,photo_id);
    	renderJson(r);
    }
    
    
    public void updateBirthday(){
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	String birthday = getPara(Fair.BIRTHDAY);
    	R r = ps.updateBirthday(user.getLong(User.ID), birthday);
    	renderJson(r);
    }
    
    
    public void updateHonners(){
    	String honners = getPara("honners");
    	int platform_id = getParaToInt("platform_id");
    	String icon = getPara("honnerIndex");
//        if(StringUtils.isNotEmpty(icon)){
//        	icon = icon.substring(icon.lastIndexOf("/")+1);
//        }
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	R r = ps.updateHonners(user.getLong(User.ID),honners,icon,platform_id);
    	renderJson(r);
    }
    
    
    @Before({Tx.class})
    public void updateXqah(){
    	String xqah = getPara("xqah");
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	R r = ps.updateXqah(user.getLong(User.ID),xqah);
    	renderJson(r);
    }
    
    
    public void updateGender(){
    	String gender = getPara(Fair.GENDER);
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	R r = ps.updateGender(user.getLong(User.ID), gender);
    	renderJson(r);
    }
    
    
    public void updateAge(){
    	int age = getParaToInt(Fair.AGE);
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	R r = ps.updateAge(user.getLong(User.ID), age);
    	renderJson(r);
    }
    
    
    public void updateArea(){
    	String province = getPara(Fair.PROVINCE);
    	String city = getPara(Fair.CITY);
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	R r = ps.updateArea(user.getLong(User.ID), province,city);
    	renderJson(r);
    }
    
    
    public void updateAvatar(){
    	String photo = getPara(Fair.PHOTO);
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	R r = ps.updateAvatar(user.getLong(User.ID),photo);
    	renderJson(r);
    }
    
    public void updateAvatarFromPhotoList(){
    	String photo = getPara(Fair.PHOTO);
    	long photo_id = getParaToLong("photo_id");
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	R r = ps.updateAvatar(user.getLong(User.ID),photo);
    	
    	String sql ="update "+FairPhoto.dao.tableName()+" set is_header=0 where wh_id=?";
		Db.update(sql,user.getLong(User.ID));
		new FairPhoto()
		.set(FairPhoto.ID, photo_id)
		.set(FairPhoto.IS_HEADER, 1).update();
    	renderJson(r);
    }
    
    @Before({Tx.class})
    public void updateScly(){
    	String scly = getPara("scly");
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	R r = ps.updateScly(user.getLong(User.ID),scly);
    	renderJson(r);
    }
    
    
    
    /**
     * 获取兴趣爱好列表
     */
    public void getXQAH(){
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        R r=ps.getXQAH(user.getLong(User.ID));
        renderJson(r);
    }
    
    
    /**
     * 获取兴趣爱好列表
     */
    public void getHonner(){
    	
        R r=ps.getHonner();
        renderJson(r);
    }

    /**
     * 获取擅长领域列表
     */
    public void getSCLY(){
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        R r=ps.getSCLY(user.getLong(User.ID));
        renderJson(r);
    }

    /**
     * 获取网红详情
     */
    public void getFairInfo(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        if (user==null){
            renderJson(R.fail("用户不存在"));
            return;
        }
        R r=ps.getFairInfo(user.getLong(User.ID)+"");
        renderJson(r);
    }

    /**
     * 设置或修改交易密码
     */
    public void setTranPwd(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        String old_pwd=getPara("old_pwd");
        String new_pwd=getPara("new_pwd");
        if (StrKit.isBlank(old_pwd) && StrKit.isBlank(new_pwd)){
            renderJson(R.fail("密码不能为空"));
            return;
        }
        long id = user.getLong(User.ID);
        R r=ps.setTranPwd(id,old_pwd,new_pwd);
        renderJson(r);
    }

    /**
     * 验证旧交易密码
     */
    public void checkTranPwd(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        String old_pwd=getPara("old_pwd");
        if (StrKit.isBlank(old_pwd)){
            renderJson(R.fail("密码不能为空"));
            return;
        }
        long id = user.getLong(User.ID);
        R r=ps.checkTranPwd(id,old_pwd);
        renderJson(r);
    }

    /**
     * 保存认证信息
     */
//    @Before(MobileFairAuthValidator.class)
    public void saveAuth(){
        Map<String,String> param  = new HashMap<>();
        param.put("user_name",getPara("user_name"));
        param.put("nick_name",getPara("nick_name"));
        param.put("fans",getPara("fans"));
        param.put("screenshot",getPara("screenshot"));
        param.put("type",getPara("type"));
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        param.put("uid",user.getLong(User.ID)+"");
        R r = new R();
		try {
			r = ps.saveAuth(param);
			renderJson(r);
		} catch (ValidateException e) {
			renderJson(r.fail(e.getMessage()));
		}
        
    }

    /**
     * 查找认证信息
     */
    public void findAuth(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        R r=ps.findAuth(user.getLong(User.ID));
        renderJson(r);
    }

    
    public void unbindAuth(){
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	long id = getParaToInt(FairAuth.ID,0);
        R r=ps.unbindAuth(id);
        renderJson(r);
    }
    
    
    
    
    
    /**
     * 获取点击数详情
     * @return
     */
    public void getClickInfo(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        R r=ps.getClickInfo(user.getLong(User.ID));
        renderJson(r);
    }

    /**
     * 获取转化数详情
     * @return
     */
    public void getCvsInfo(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        R r=ps.getCvsInfo(user.getLong(User.ID));
        renderJson(r);
    }

    /**
     * 个人中心数据
     * @return
     */
    public void center(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        R r=ps.center(user.getLong(User.ID));
        renderJson(r);
    }

    /**
     * 获取收益数据
     */
    public void getWallet(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        R r=ps.getWallet(user.getLong(User.ID));
        renderJson(r);
    }

    /**
     * 验证交易密码是否正确
     */
    public void checkNowTranPwd(){
        String tranPwd = getPara("tranPwd");
        if (StrKit.isBlank(tranPwd)){
            renderJson(R.fail("交易密码不能为空"));
            return;
        }
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        R r=ps.checkTranPwd(tranPwd,user.getLong(User.ID));
        renderJson(r);
    }

    /**
     * 提现
     */
    @Before(Tx.class)
    public void withdraw(){
        String money = getPara("money");
        String bankId = getPara("bankId");
        String wdToken = getPara("wdToken");
        String branch = getPara("branch");
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        if (StrKit.isBlank(wdToken)){
            renderJson(R.fail("wdToken不能为空"));
            return;
        }
        if (StrKit.isBlank(bankId)){
            renderJson(R.fail("bankId不能为空"));
            return;
        }
        if (StrKit.isBlank(money)){
            renderJson(R.fail("money不能为空"));
            return;
        }
        if (!U.isMoney(money)){
            renderJson(R.fail("提现金额格式不正确"));
            return;
        }
        R r=ps.withdraw(money,user.getLong(User.ID),wdToken,bankId);
        renderJson(r);
    }

    /**
     * 保存网红照片
     */
    public void savePhoto(){
        String url = getPara("url");
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        long uid =user.getLong(User.ID);
        R r=ps.savePhoto(uid,url);
        renderJson(r);
    }

    /**
     * 获取网红照片
     */
    public void getPhoto(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        long uid =user.getLong(User.ID);
        R r=ps.getPhoto(uid);
        renderJson(r);
    }



    /**
     * 删除照片
     */
    public void delPhoto(){
        User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        long uid = user.getLong(User.ID);
        String id = getPara("id");
        R r=ps.delPhoto(uid,id);
        renderJson(r);
    }


    
    public void yandou(){
    	
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	R r = R.ok("成功");
//    	Fair fair = Fair.dao.findById(user.getLong(User.ID));
//    	String sql="select count(id) as id from "+Fair.dao.tableName()+" where money>? order by money desc";
//    	Fair temp = Fair.dao.findFirst(sql,fair.getDouble(Fair.MONEY));
//    	int sort = (temp.getInt(Fair.ID)==0)?1:temp.getInt(Fair.ID)+1;
//    	
//    	sql = "select sum(money) as money from "+FairWithdraw.dao.tableName()+" where status=? and wh_id=?";
//    	FairWithdraw withDraw = FairWithdraw.dao.findFirst(sql,FairWithdraw.STATUS_SUCCESS,user.getLong(User.ID));
    	
    	MoneyLog sumlog = MoneyLog.dao
				.findFirst("select SUM(money) as money from " + MoneyLog.dao.tableName() + " where wh_id=? and deletetag=? and state=? ", 
						user.getLong(User.ID),MoneyLog.STATUS_SUCCESS,MoneyLog.STATE_ADD);
    	double totalFee = (sumlog.getDouble("money")==null)?0:sumlog.getDouble("money");
    	int yandou = (int)(totalFee/100);
    	
    	//检测所有登录用户的收益信息，并且存入数据表中分析
    	if(totalFee>=0){
    		TaskCalculateService.ME.syncTotalProfit(totalFee, user.getLong(User.ID));
    	}
    	String sql="select count(id) as id from fair_total_profit where profit>? order by profit desc";
    	Record temp =Db.findFirst(sql,totalFee);
    	int sort = (temp.getInt("id")==0)?1:temp.getInt("id")+1;
    	r.p("sort", sort);
    	r.p("yandou",yandou);
    	renderJson(r);
    }
    
    
    public void isSetTransPwd(){
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
    	boolean result = ps.isSetTransPwd(user.getLong(User.ID));
    	R r = R.ok("成功");
    	r.p("isSetTransPwd",result);
    	r.p("isOpen",ps.isOpenSMS(user.getLong(User.ID)));
    	renderJson(r);
    }
    
    public void uploadAvatar() throws Exception {
        UploadFile upfile=getFile();
        String category  = getPara("category","pc-");
        try {
            String upload = QiNiuUtil.upload(new FileInputStream(upfile.getFile()),category);
            upfile.getFile().delete();
            R r = R.ok("成功");
        	r.p("savepath",upload);
        } catch (Exception e) {
            throw e;
        }
    }

    public void deleteHonner(){
    	int id = getParaToInt("id");
    	renderJson(ps.deleteHonner(id));
    }
    
    public void setPublicPhoto(){
    	int id = getParaToInt("photo_id",0);
    	renderJson(ps.setPublicPhoto(id));
    }
    
    public void cancelPublicPhoto(){
    	int id = getParaToInt("photo_id",0);
    	renderJson(ps.cancelPublicPhoto(id));
    }
    
    public void queryHonnersOfMine(){
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        long  uid = user.getLong(User.ID);
        renderJson(ps.queryHonnersOfMine(uid));
    }
    
    
    public void smsSet(){
    	boolean status = getParaToBoolean("status");
    	User user= UserUtil.getCurrentUser(getPara("token"),"ios");
        long  uid = user.getLong(User.ID);
        R r = R.ok("成功");
        Fair t = Fair.dao.findById(uid);
        t.set(Fair.SMS_SET, status).update();
        r.p("isOpen",status);
    	renderJson(r);
    }
}
